package com.example.junit5demo;

import com.example.junit5demo.controller.AccountController;
import com.example.junit5demo.controller.DemoController;
import com.example.junit5demo.service.AccountService;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

/**
 * 写法1：SpringBootTest+AutoConfigureMockMvc
 */
//@SpringBootTest
//@AutoConfigureMockMvc

/**
 * 写法2：WebMvcTest指定控制器
 */
@WebMvcTest(AccountController.class)
public class MockBeanTest_Autowired {
    private static final Logger log = LoggerFactory.getLogger(DemoController.class);

    /**
     * 写法1与写法2都可以@Autowired
     */
    @Autowired
    private MockMvc mockMvc;

    /**
     * 可以不需要注入accountController
     */
//    @Autowired
//    private AccountController accountController;

    @MockBean
    private AccountService accountService;


    @Test
    @DisplayName("mock Service")
    public void test() throws Exception {

        // (2)模拟外部依赖返回结果
        Mockito.when(accountService.getInfo(Mockito.any(String.class))).thenReturn("mock msg");

        // (3)构建请求
        MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/account/info");

        // (4)发送请求，获取请求结果
        ResultActions perform = mockMvc.perform(request);

        // (5)请求结果校验
        perform.andExpect(MockMvcResultMatchers.status().isOk());

        MvcResult mvcResult = perform
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        // (6)校验返回信息
        log.info("response:" + response.getContentAsString());
    }
}

